import java.util.ArrayList;
import java.util.List;

//括号生成
//测试链接：https://leetcode.cn/problems/generate-parentheses/
public class GenerateParenthesis {
    List<String> ans;
    StringBuilder path;
    int left = 0, right = 0;
    public List<String> generateParenthesis(int n) {
        ans = new ArrayList<>();
        path = new StringBuilder();

        dfs(n);
        return ans;
    }

    //left,right分别表示左括号和右括号的数量
    public void dfs(int n) {
        if(path.length() == 2*n) {
            ans.add(path.toString());
            return;
        }

        path.append('(');
        if(left + right < 2*n && left < n) {
            left++;
            dfs(n);
            path.deleteCharAt(path.length() - 1);
            left--;
        }else {
            path.deleteCharAt(path.length() - 1);
        }

        path.append(')');
        if(left + right < 2*n && right < left) {
            right++;
            dfs(n);
            path.deleteCharAt(path.length() - 1);
            right--;
        }else {
            path.deleteCharAt(path.length() - 1);
        }
    }
}
